package com.cqs.leetcode.math;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lixiaowen
 * @create 2020-01-02
 */
public class Combinations77 {


    /**
     * 回溯法
     */
    static class Solution {

        public List<List<Integer>> combine(int n, int k) {
            List<List<Integer>> result = new ArrayList<>();
            combination(n, k, new ArrayList<>(), result);
            return result;
        }

        private void combination(final int n, final int k, final ArrayList<Integer> list, List<List<Integer>> result) {
            if (k == 0) {
                result.add(new ArrayList<>(list));
                return;
            }
            //注意这里防止重复 --- 所有的组合:每一组均按照升序列排列
            int i = list.size() == 0 ? 1 : 1 + list.get(list.size() - 1);
            //(n-i+1)>=k 减去不必要的分支
            for (; i <= n && (n - i + 1) >= k; i++) {
                list.add(i);
                combination(n, k - 1, list, result);
                list.remove(list.size() - 1);
            }
        }
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        Map<Integer, Integer> cases = new LinkedHashMap<>();
        cases.put(3, 2);
        cases.put(5, 3);
        cases.put(4, 2);
        cases.put(6, 6);
        cases.forEach((k, v) -> {
            List<List<Integer>> combine = solution.combine(k, v);
            System.out.println("m:" + k + "\t n:" + v + "\tresult:" + combine);
        });
    }
}
